package websokect

import (
	"context"
	"fmt"
	"net/http"
	"sync"
	"time"
	D "websocket_apn/define"
	"websocket_apn/log"
	"websocket_apn/proto"

	"github.com/gorilla/websocket"
)

//socket锁
var mutex = &sync.Mutex{}

//websocket客户端
var clientConn *websocket.Conn

//连接列表
var connecting = make(map[string]bool)

//HTransfer http_transfer结构体
type WebTransfer struct {
	webServer string

	url  string
	ctx  context.Context
	cc   context.CancelFunc
	resp *http.Response
}

//NewHTTPTransfer 新建http通讯器
func NewWebTransfer(param Param) (*WebTransfer, error) {
	ht := &WebTransfer{
		webServer: param.WebServer,
	}
	ht.Init()
	return ht, nil
}

func (ht *WebTransfer) Init() {
	if clientConn == nil {
		// Connect to the target WebSocket server
		client, _, err := websocket.DefaultDialer.Dial(ht.webServer, nil)
		if err != nil {
			log.Error("dial target:", err)
			return
		}
		clientConn = client
	}
}

//Send 发送
func (ht *WebTransfer) Send(m *D.Message) D.ErrorCode {
	//ht.ctx, ht.cc = context.WithTimeout(context.Background(), ht.timeout*time.Millisecond)
	//req = req.WithContext(ht.ctx)
	mutex.Lock()
	mutex.Unlock()
	if len(m.PayloadBytes) > 0 {
		log.Debugf("web send[%4d]: %s", len(m.PayloadBytes), proto.HexToHexStr(m.PayloadBytes))
	}
	if clientConn != nil {
		// Send the message to the target server
		err := clientConn.WriteMessage(m.MessageType, m.PayloadBytes)
		if err != nil {
			log.Error("write to Websocket:", err)
			time.Sleep(1000 * time.Millisecond)
			return D.ErrorTransferSendError
		}
		time.Sleep(300 * time.Millisecond)
		return D.Success
	} else {
		return D.ErrorUnknown
	}
}

//Receive 接收
func (ht *WebTransfer) Receive(length int, msgId int32) (D.ErrorCode, *D.Message) {
	err := fmt.Errorf("")
	msg := &D.Message{}

	msg.MessageType, msg.PayloadBytes, err = clientConn.ReadMessage()
	if err != nil {
		log.Error("read from Websocket:", err)
		return D.ErrorTransferReceiveError, nil
	}
	if len(msg.PayloadBytes) > 0 {
		log.Debugf("web recv[%4d]: %s", len(msg.PayloadBytes), proto.HexToHexStr(msg.PayloadBytes))
	}
	return D.Success, msg
}

//Close 关闭
func (ht *WebTransfer) Close() {
	clientConn.Close()
}
